package com.example.zhaohang.employmentapp;

import android.Manifest;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.baidu.ocr.sdk.OCR;
import com.baidu.ocr.sdk.OnResultListener;
import com.baidu.ocr.sdk.exception.OCRError;
import com.baidu.ocr.sdk.model.AccessToken;
import com.baidu.ocr.sdk.model.IDCardParams;
import com.baidu.ocr.sdk.model.IDCardResult;
import com.baidu.ocr.ui.camera.CameraActivity;
import com.bigkoo.pickerview.TimePickerView;
import com.example.zhaohang.utils.BitmapFileSetting;
import com.example.zhaohang.utils.FileUtil;
import com.example.zhaohang.utils.ImageUtil;
import com.example.zhaohang.utils.ToastMake;
import com.example.zhaohang.utils.Utils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import de.hdodenhof.circleimageview.CircleImageView;
import kr.co.namee.permissiongen.PermissionFail;
import kr.co.namee.permissiongen.PermissionGen;
import kr.co.namee.permissiongen.PermissionSuccess;

public class BasicInfoActivity extends BasicActivity implements View.OnClickListener {

    private static final int PHOTOANDSD_PERMISS = 101;
    private static final int    IMAGE_ONE_ONE = 101;
    private              String IMAGE_TYPE    = "image/*";
    private static final int REQ_2 = 4;
    private TextView        mName1;
    private CircleImageView mProfileImage;
    private TextView        mText1;
    private EditText        mName4;
    private EditText        mName2;
    private TextView        mName7;
    private RelativeLayout  mName8;
    private String          mFilePath;
    private Bitmap          mStream;
    private Uri             mOriginalUri;
    private static final int     REQUEST_CODE_CAMERA = 102;
    private              boolean isIcon              = false;
    private              boolean isID                = false;
    private AlertDialog.Builder alertDialog;
    private ImageView           mImage;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView_V(R.layout.activity_basic_info);

        alertDialog = new AlertDialog.Builder(this);
        //申请身份证识别软件
        OCR.getInstance().initAccessTokenWithAkSk(new OnResultListener<AccessToken>() {
            @Override
            public void onResult(AccessToken result) {
                // 调用成功，返回AccessToken对象
                String token = result.getAccessToken();
            }

            @Override
            public void onError(OCRError error) {
                // 调用失败，返回OCRError子类SDKError对象
            }
        }, getApplicationContext(), "eObHLWhFpeTt9LXkaEXU0Vmm", "G3x0bzSL6WzcU2AOPjMch75EnL6kjHx3");


        //先指定路径
        mFilePath = Environment.getExternalStorageDirectory().getAbsolutePath();
        mFilePath = mFilePath + "/" + File.separator + ".jpg";
        mName1 = (TextView) findViewById(R.id.name1);
        mText1 = (TextView) findViewById(R.id.text1);
        mName7 = (TextView) findViewById(R.id.name7);

        mImage = (ImageView) findViewById(R.id.image);


        mProfileImage = (CircleImageView) findViewById(R.id.profile_image);
        mName8 = (RelativeLayout) findViewById(R.id.name8);


        mName4 = (EditText) findViewById(R.id.name4);
        mName2 = (EditText) findViewById(R.id.name2);

        mProfileImage.setOnClickListener(this);
        mName1.setOnClickListener(this);
        mName8.setOnClickListener(this);
        mName7.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {

            //更换头像
            case R.id.profile_image:
                hasPermission();
                isIcon = true;
                break;

            //下一步
            case R.id.name1:
                String name = mName4.getText().toString().trim();
                String id = mName2.getText().toString().trim();
                String time = mName7.getText().toString().trim();
                if (mStream==null){
                    ToastMake.showToast("请上传头像");
                    return;
                }
                if (mName4==null||TextUtils.equals(name,"")){
                    ToastMake.showToast("姓名不能为空");
                    return;
                }
                if (mName2==null||TextUtils.equals(id,"")){
                    ToastMake.showToast("身份证号码不能为空");
                    return;
                }
                if (!Utils.isIdNumber(id)){
                   return;
                }
                //TODO:并且选择时间不能大于当前的时间
                if (time.contains("//")){
                    ToastMake.showToast("领取驾照时间不能为空");
                    return;
                }


                Intent intent = new Intent();
                intent.setClass(BasicInfoActivity.this, CarInformationActivity.class);
                MyApplayCation.driverInfo.setCard(name);
                MyApplayCation.driverInfo.setName(id);
                MyApplayCation.driverInfo.setReceive(time);

                startActivity(intent);

                break;
            //身份证
            case R.id.name8:
                isID = true;
                hasPermission();

                break;
            //选择时间
            case R.id.name7:
                TimePickerView pvTime = new TimePickerView.Builder(BasicInfoActivity.this, new TimePickerView.OnTimeSelectListener() {
                    @RequiresApi(api = Build.VERSION_CODES.N)
                    @Override
                    public void onTimeSelect(Date date2, View v) {//选中事件回调

                        long chioceDate = Utils.dateToLong(date2);
                        long curDate = Utils.getCurDate();
                        if (chioceDate>=curDate){
                            ToastMake.showToast("时间必须小于当前时间");
                            return ;
                        }else {
                            String time = getTime(date2);
                            mName7.setText(time);
                            mName7.setTextColor(getResources().getColor(R.color.textColor5));
                        }
                    }
                })
                        .setType(TimePickerView.Type.YEAR_MONTH_DAY)//默认全部显示
                        .setCancelText("取消")//取消按钮文字
                        .setSubmitText("确定")//确认按钮文字
                        .setContentSize(20)//滚轮文字大小
                        .setTitleSize(20)//标题文字大小
                        .setTitleText("请选择时间")//标题文字
                        .setOutSideCancelable(true)//点击屏幕，点在控件外部范围时，是否取消显示
                        .isCyclic(true)//是否循环滚动
                        .setTextColorCenter(Color.BLACK)//设置选中项的颜色
                        .setTitleColor(Color.BLACK)//标题文字颜色
                        .setSubmitColor(Color.BLUE)//确定按钮文字颜色
                        .setCancelColor(Color.BLUE)//取消按钮文字颜色
                        //                        .setTitleBgColor(0xFF666666)//标题背景颜色 Night mode
                        //                        .setBgColor(0xFF333333)//滚轮背景颜色 Night mode
                        //                        .setRange(calendar.get(Calendar.YEAR) - 20, calendar.get(Calendar.YEAR) + 20)//默认是1900-2100年
                        //                        .setDate(selectedDate)// 如果不设置的话，默认是系统时间*/
                        //                        .setRangDate(startDate,endDate)//起始终止年月日设定
                        //                        .setLabel("年","月","日","时","分","秒")
                        .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                        //                        .isDialog(true)//是否显示为对话框样式
                        .build();
                pvTime.setDate(Calendar.getInstance());//注：根据需求来决定是否使用该方法（一般是精确到秒的情况），此项可以在弹出选择器的时候重新设置当前时间，避免在初始化之后由于时间已经设定，导致选中时间与当前时间不匹配的问题。
                pvTime.show();
                break;
        }

    }
    private void hasPermission() {
        PermissionGen.with(BasicInfoActivity.this)
                .addRequestCode(PHOTOANDSD_PERMISS)
                .permissions(
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.CAMERA
                )
                .request();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) {
        PermissionGen.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
    }

    @PermissionSuccess(requestCode = PHOTOANDSD_PERMISS)
    public void requestPhotoSuccess() {
        //成功之后的处理

        if (isIcon) {
            isIcon = false;
            isID = false;
            showChoiceDialog();

        } else if (isID) {
            isID = false;
            isIcon = false;
            readID();

        }
    }

    private void readID() {

        Intent intent = new Intent(BasicInfoActivity.this, CameraActivity.class);
        intent.putExtra(CameraActivity.KEY_OUTPUT_FILE_PATH,
                FileUtil.getSaveFile(getApplication()).getAbsolutePath());
        intent.putExtra(CameraActivity.KEY_CONTENT_TYPE, CameraActivity.CONTENT_TYPE_ID_CARD_FRONT);
        startActivityForResult(intent, REQUEST_CODE_CAMERA);

    }

    @PermissionFail(requestCode = PHOTOANDSD_PERMISS)
    public void requestPhotoFail() {
        //失败之后的处理，我一般是跳到设置界面

        boolean sdPermission = ActivityCompat.shouldShowRequestPermissionRationale(BasicInfoActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
        boolean camPermission = ActivityCompat.shouldShowRequestPermissionRationale(BasicInfoActivity.this, Manifest.permission.CAMERA);

        if (sdPermission || camPermission) {
            Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
            //        Uri uri = Uri.fromParts("package", context.getPackageName());
            //        intent.setData(uri);
            intent.setData(Uri.parse("package:" + getPackageName()));
            startActivity(intent);
        }

    }

    private void showChoiceDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(BasicInfoActivity.this);
        builder.setTitle("选择照片来源");
        final String[] single_list = {"相册", "相机"};
        builder.setSingleChoiceItems(single_list, 0, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                String str = single_list[which];
                if (str.equals("相册")) {
                    //这里读取相册
                    onStartPhotoPicture();

                } else {
                    //这里读取相机
                    startBigCameral();
                }
                dialog.dismiss();
            }
        });
        AlertDialog dialog = builder.create();
        dialog.show();
    }


    private void onStartPhotoPicture() {
        // TODO Auto-generated method stub
        boolean isKitKatO = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
        Intent getAlbum;
        if (isKitKatO) {
            getAlbum = new Intent(Intent.ACTION_OPEN_DOCUMENT);
        } else {
            getAlbum = new Intent(Intent.ACTION_GET_CONTENT);
        }
        getAlbum.setType(IMAGE_TYPE);
        startActivityForResult(getAlbum, IMAGE_ONE_ONE);
    }

    //调取大图
    public void startBigCameral() {


        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        startActivityForResult(intent, REQ_2);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {

            //获取相机照片
            if (requestCode == REQ_2) {

                mStream = data.getParcelableExtra("data");
                mProfileImage.setImageBitmap(mStream);
                mText1.setVisibility(View.GONE);
                File file = BitmapFileSetting.saveBitmapFile(mStream, mFilePath);
                //设置头像信息并保存起来
                MyApplayCation.driverInfo.setIcon(file);

                //获取相册照片
            } else if (requestCode == IMAGE_ONE_ONE) {
                ContentResolver resolver = getContentResolver();
                //获得图片的uri
                mOriginalUri = data.getData();
                mText1.setVisibility(View.GONE);
                //这里已经对获得照片进行了压缩处理
                try {
                    mStream = ImageUtil.getImage(MediaStore.Images.Media.getBitmap(resolver, mOriginalUri));
                    mProfileImage.setImageBitmap(mStream);
                    File file = BitmapFileSetting.saveBitmapFile(mStream, mFilePath);
                    //设置头像信息并保存起来
                    MyApplayCation.driverInfo.setIcon(file);
                } catch (IOException e) {
                    e.printStackTrace();
                    mText1.setVisibility(View.VISIBLE);
                }

                //读取身份证照片
            } else if (requestCode == REQUEST_CODE_CAMERA) {
                if (data != null) {
                    String contentType = data.getStringExtra(CameraActivity.KEY_CONTENT_TYPE);
                    String filePath = FileUtil.getSaveFile(getApplicationContext()).getAbsolutePath();
                    if (!TextUtils.isEmpty(contentType)) {
                        if (CameraActivity.CONTENT_TYPE_ID_CARD_FRONT.equals(contentType)) {
                            recIDCard(IDCardParams.ID_CARD_SIDE_FRONT, filePath);
                        } else if (CameraActivity.CONTENT_TYPE_ID_CARD_BACK.equals(contentType)) {
                            recIDCard(IDCardParams.ID_CARD_SIDE_BACK, filePath);
                        }
                    }
                }
            }
        }
    }

    private void recIDCard(String idCardSide, String filePath) {
        IDCardParams param = new IDCardParams();
        param.setImageFile(new File(filePath));
        // 设置身份证正反面
        param.setIdCardSide(idCardSide);
        File imageFile = param.getImageFile();

        //保存身份证的照片向后台传递
        MyApplayCation.driverInfo.setId(imageFile);
        //设置图片
        mImage.setImageBitmap(getPicFromBytes(File2Bytes(imageFile), null));

        // 设置方向检测
        param.setDetectDirection(true);
        // 设置图像参数压缩质量0-100, 越大图像质量越好但是请求时间越长。 不设置则默认值为20
        param.setImageQuality(20);

        //TODO：获取身份证上的信息，并对身份证上的信息进行核对
        OCR.getInstance().recognizeIDCard(param, new OnResultListener<IDCardResult>() {
            @Override
            public void onResult(IDCardResult result) {
                if (result != null) {
                    alertText("", result.toString());
                }
            }

            @Override
            public void onError(OCRError error) {
                alertText("", getResources().getString(R.string.string25));
            }
        });
    }

    private void alertText(final String title, final String message) {
        this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                alertDialog.setTitle(title)
                        .setMessage(message)
                        .setPositiveButton("确定", null)
                        .show();
            }
        });
    }

    /**
     * @param file 将本地文件转化为字节流
     * @return 图片的字节流
     */
    public byte[] File2Bytes(File file) {
        int byte_size = 1024;
        byte[] b = new byte[byte_size];
        try {
            FileInputStream fileInputStream = new FileInputStream(file);
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream(
                    byte_size);
            for (int length; (length = fileInputStream.read(b)) != -1; ) {
                outputStream.write(b, 0, length);
            }
            fileInputStream.close();
            outputStream.close();
            return outputStream.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * @param bytes 将字节流转化为bitmap
     * @param opts
     * @return
     */
    public Bitmap getPicFromBytes(byte[] bytes,
                                  BitmapFactory.Options opts) {
        if (bytes != null)
            if (opts != null)
                return BitmapFactory.decodeByteArray(bytes, 0, bytes.length,
                        opts);
            else
                return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
        return null;
    }

    public String getTime(Date date) {//可根据需要自行截取数据显示
        SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
        return format.format(date);
    }


}
